<?php
namespace Article\Model;
use Think\Model;
/**
 * huhaiqin,2023.03.22
 * 文章数据逻辑部分
 */
class ArticleModel extends Model{

    /**
     * huhaiqin，2023.03.23
     * 检测权限
     * param $check_role string 检测角色
     */
    private function _check_auth($check_role = 'admin'){
        if(!$_SESSION['loginUser']){
            _apiReturn(0,'请先登录~');
        }
        if($check_role == 'admin'){
            if($_SESSION['loginUser']['role'] != 'admin'){
                _apiReturn(0,'您没有权限执行该操作~');
            }
        }
    }

    /**
     * huhaiqin，2023.05.23
     * 根据文章和用户ID
     * huhaiqin,2023.07.07
     * 优化
     */
    public function _find($id = 0){
        if(!$id){
            _apiReturn(0,'参数不合法~');
        }

        $sql = "SELECT A.*,C.cat_name as catname,B.`username`,B.`realname`,B.avatar,B.role FROM mini_article A LEFT JOIN mini_users B ON A.`uid` = B.`id` left join mini_cats C on A.cid = C.id WHERE A.id = ".$id." limit 1";
        $data = $this->query($sql);
        $result = $data[0];
        $result['imglist'] = json_decode($result['imglist'],true);
        // $data['imglist'] = json_decode($data['imglist'],true);
        return $result;
    }

    /**
     * huhaiqin,2023.03.23
     * 添加、编辑文章
     */
    public function _edit($post=[]){
        if($post['title'] == ''){
            _apiReturn(0,'文章标题不能为空~');
        }
        if($post['imglist_web']){
            $tmpImgList = [];
            for($i = 0 ; $i < count($post['imglist']);$i++){
                $tmpImgList[$i] = json_decode($post['imglist'][$i],true);
            }
            $post['imglist'] = json_encode($tmpImgList,JSON_UNESCAPED_UNICODE);
        }else{
            $post['imglist'] = json_encode($post['imglist'],JSON_UNESCAPED_UNICODE);
        }
        if(!$post['cid']){
            $post['cid'] = C('Default_Cid'); //如果传过来分类ID，则加上默认分类ID
        }
        $post['update_time'] = time();
        $data = $this->create($post);
        $data['uid'] = $post['uid'] ? $post['uid'] : $_SESSION['loginUser']['id']; //用户ID优先使用post过来的，默认使用当前登录账户
        if(!$data['uid']){
            _apiReturn(0,'请先登录~');
        }
        if($data['id']){
            $checkUser = D('Users')->field('id,role')->find($data['uid']);
            if($checkUser['role']!='admin'){
                unset($data['uid']); //管理员有权限改变数据归属
                //需要检测是否有权限修改
                $map = ['uid'=>$checkUser['id'],'id'=>$data['id']];
                $check = $this->where($map)->find();
                if(!$check){
                    _apiReturn(0,'对不起，只有创建者或管理员有权限编辑~');
                }
            }
            if($this->save($data)){
                _apiReturn(1,'success',$data);
            }else{
                _apiReturn(0,'修改失败~');
            }
        }else{
            $data['create_time'] = time();
            $data['id'] = $this->add($data);
            if($data['id']){
                _apiReturn(1,'success',$data);
            }else{
                _apiReturn(0,'添加失败~');
            }
        }
    }

    /**
     * huhaiqin,2023.03.22
     * 数据列表接口
     * param $p int 当前页码
     * param $row int 一页记录数
     * param $query string 查询的sql语句
     */
    public function _query($p = 1 , $row = 10 , $query = ''){
        $sql = "SELECT A.*,C.cat_name as catname,B.`username`,B.`realname`,B.avatar,B.role FROM mini_article A LEFT JOIN mini_users B ON A.`uid` = B.`id` left join mini_cats C on A.cid = C.id WHERE 1=1 ";
        $sqlcount = "SELECT COUNT(DISTINCT A.`id`) AS tp_count FROM mini_article A LEFT JOIN mini_users B ON A.`uid` = B.`id` left join mini_cats C on A.cid = C.id WHERE 1=1 ";
        if($query){
            $sql .= $query;
            $sqlcount .= $query;
        }
        //order
        $sql .= " ORDER BY A.listorder asc,A.id desc";
        $sql .= " LIMIT ".($p-1) * $row.",".$row;
        $data['data'] = $this->query($sql);       
        $total = $this->query($sqlcount);
        $data['page']['total'] = $total[0]['tp_count'];
        //处理删除最后一条数据的时候没有数据的bug,请求最后一页没有数据的bug
        if($data['page']['total']>0){
            if (floor(($data['page']['total'] + $row - 1) / $row) < $p) {
                $p = $p - 1;
            }
        }
        //页数数据
        $data['page']['count'] = (int)(($data['page']['total'] + $row -1) / $row);
        $data['page']['cur'] = $p;
        $data['page']['row'] = $row;
        // $data['sql'] = $sql;
        return $data;
    }


    /**
     * huhaiqin,2023.03.22
     * 删除文章
     */
    public function _del($uid=0,$ids = []){
        if(count($ids) == 0 || !$ids){
            _apiReturn(0,'文章ID不能为空~');
        }
        if($_SESSION['loginUser']['role'] == 'admin'){
            //如果是管理员，则直接放行
            $map['id'] = ['in',$ids];
        }else{
            if(!$uid){
                _apiReturn(0,'检测不到用户');
            }
            $map = [
                'id' => ['in',$ids],
                'uid' => $uid
            ];
        }
        
        if($this->where($map)->delete()){
            _apiReturn(1,'success');
            //文章删除成功后，删除文章的所有评论
            // $keys = [];
            // if(gettype($ids) == "string"){
            //     array_push($keys, 'user-' . $ids);
            // }elseif(gettype($ids) == "array"){
            //     foreach ($ids as $id) {
            //         array_push($keys, 'user-' . $id);
            //     }
            // }
            // if(count($keys) > 0){
            //     D('Comment/Comment')->_del_comments_by_key($keys);
            // }
        }else{
            _apiReturn(0,'error');
        }
    }

    /**
     * xqx,2023.07.22
     * 前端获取文章列表接口
     * param $cur int 当前在第几条
     * param $size int 一次读取条数
     * param $query string 查询的sql语句
     */
    public function _select($cur = 0 , $size = 10 , $query = ''){
        $sql = "SELECT A.*,C.cat_name as catname,B.`username`,B.`realname`,B.avatar,B.role FROM mini_article A LEFT JOIN mini_users B ON A.`uid` = B.`id` left join mini_cats C on A.cid = C.id WHERE 1=1 ";
        $sqlcount = "SELECT COUNT(DISTINCT A.`id`) AS tp_count FROM mini_article A LEFT JOIN mini_users B ON A.`uid` = B.`id` left join mini_cats C on A.cid = C.id WHERE 1=1 ";
        if($query){
            $sql .= $query;
            $sqlcount .= $query;
        }
        //order
        $sql .= " ORDER BY A.listorder asc,A.id desc";
        $sql .= " LIMIT ".$cur.",".$size;
        $data['data'] = $this->query($sql);       
        $total = $this->query($sqlcount);
        $data['page']['total'] = $total[0]['tp_count'];
        $data['page']['cur'] = $cur + $size;
        // $data['sql'] = $sql;
        return $data;
    }
}